<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> axios 的由来</title>
<!--     <script src="../node_modules/axios/dist/mine-axios.js"></script>-->
</head>
<body>
    <script type="text/javascript">
        function Axios(config) {
            this.defaults = config;
            this.interceptors = {
                request: {},
                response: {}
            };
        }

        Axios.prototype.request = function (config) {
            console.log(`发送ajax请求，method: ${config.method}`);
        };

        // 通过prototype添加相关方法
        Axios.prototype.get = function (config) {
            console.log("发送ajax Get请求");
            return this.request({
                method:"GET"
            });
        };

        Axios.prototype.post = function (config) {
            console.log("发送ajax Post请求");
            return this.request({
                method: "POST"
            });
        };

        // 声明方法
        function createInstance(config) {
            // 实例化一个对象
            let context = new Axios(config);
            // 创建请求函数
            let instance = Axios.prototype.request.bind(context);
            // 将Axios.prototype对象中的方法添加到instance函数对象中
            Object.keys(Axios.prototype).forEach((key) => {
                instance[key] = Axios.prototype[key].bind(context);
            });
            // 为instance添加defaults、interceptors
            Object.keys(context).forEach((key) => {
                instance[key] = context[key];
            });
            // console.dir(instance);
            return instance;
        }

        let axios = createInstance();
        axios({method: "GET"});
        axios.get({});
        axios.post({});
    </script>
</body>
</html>